<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
	*{font-size: 20px;}
	</style>
</head>
<body>
	<h1><center>表单验证</center></h1>
	<hr>
	<form action="1.php" method="post" name="regForm" onsubmit="return checkForm()">
		<table align="center">
			<tr>
				<td>*邮箱</td>
				<td><input type="text" name="email"></td>
				<td id="emailtab">* 必填项,请输入常用邮箱</td>
			</tr>
			<tr>
				<td>*用户名</td>
				<td><input type="text" name="username"></td>
				<td id="usernametab">* 必填项,请输入用户名(数字字母下划线)</td>
			</tr>
			<tr>
				<td>*密码</td>
				<td><input type="password" name="pwd"></td>
				<td id="pwdtab">* 必填项,请输入6-12位的密码</td>
			</tr><tr>
				<td>*重复密码</td>
				<td><input type="password" name="repwd"></td>
				<td id="repwdtab">* 必填项,请再输入一次密码</td>
			</tr>
			<tr>
				<td></td>
				<td><input type="submit" value="注 册"></td>
			</tr>
		</table>
	</form>
<script>

	//表单验证函数
	function checkForm () {
		//验证邮箱
		var email = document.regForm.email.value;
		var et = document.getElementById('emailtab');
		if (email.search(/^[\w-]+@[\w-]+(\.\w+){1,3}$/) === -1) {
			et.style.color = '#f00';
			et.innerHTML = '× 邮箱输入有误,请重新输入';
			return false;
		}else{
			et.style.color = '#0a0';
			et.innerHTML = '√ 通过';
		}

		//验证用户名
		var uv = document.regForm.username.value;
		var ut = document.getElementById('usernametab');
		if (uv.match(/^\w{6,12}$/) === null) {
			ut.style.color = '#f00';
			ut.innerHTML = '× 用户名须由6-12位数字字母下划线组成';
			return	false;
		}else{
			ut.style.color = '#0a0';
			ut.innerHTML = '√ 通过';
		}

		//验证密码
		var pwd = document.regForm.pwd.value;
		var pt = document.getElementById('pwdtab');
		if (pwd.length<6 || pwd.length>12) {
			pt.style.color = '#f00';
			pt.innerHTML = '× 密码不合法';
			return false;
		}else{
			pt.style.color = '#0a0';
			pt.innerHTML = '√ 通过';
		}

		//重复密码判断
		var repwd = document.regForm.repwd.value;
		var rpt = document.getElementById('repwdtab');
		if (repwd !== pwd) {
			rpt.style.color = '#f00';
			rpt.innerHTML = '× 两次输入不一致';
			return false;
		}else{
			rpt.style.color = '#0a0';
			rpt.innerHTML = '√ 通过';
		}

		return true;
	}
</script>
</body>
</html>